package com.kuafu.latte.transport.client;

import com.kuafu.latte.exchange.DefaultPackage;
import com.kuafu.latte.exchange.Message;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClientHandler extends ChannelDuplexHandler {

    private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

    private NettyClient client;

    public NettyClientHandler(NettyClient client){
        this.client = client;
    }
    //获取数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object response) throws Exception {
        logger.debug("receive data {}",response);
        DefaultPackage.received(ctx.channel(), (Message) response);
    }

    //与服务器建立连接
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("channel active");
    }

    //与服务器断开连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.error("channel inactive");
        client.doConnect();
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭管道
        ctx.channel().close();
        //打印异常信息
        logger.error(cause.getMessage(),cause);
    }
}
